<html>
<!--
http://code.google.com/p/bobchess/
Copyright (C) 2008, 2009 James (james at doubtlesshouse dot org dot uk)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Revision $Revision: 60 $ checked in $Date: 2010-04-06 22:11:54 +0000 (Tue, 06 Apr 2010) $
                                                            -->

<head>
<title>Bob The Chess Clock</title>
<style type="text/css">
h1 { 
	color: #400000; 
	text-align: center; 
	font-family: sans-serif; 
}
fieldset { 
	padding: 10px; 
	-moz-border-radius:4px; 
	-webkit-border-radius: 4px;
	border-radius: 4px;
}
span.error { 
	color: red; 
	font-style:italic; 
}
div.helpbox { 
	margin: 10px; 
	float: right; 
	width: 20%; 
	padding: 10px; 
	background-color: #400000; 
	color: white;  
	-moz-border-radius:4px; 
	-webkit-border-radius: 4px;
	border-radius: 4px;
}
div.helpbox h2 {
	text-align:center;
}
div#play {
	display:block;
	height:99%;
	text-align:center;
	width:99%;
}
div#play table {
	width:99%; 
	height:70%;
}
div#play table td {
	width:50%;
	padding: 10px;
}
div#SimpleDelayDisplay {
	font-size:200%;
	text-align:center;
	width:99%;
}
div#play table td input {
	font-size:300%;	
	height:100%;
	padding:10px;
	width:100%;
	-moz-border-radius:10px; 
	-webkit-border-radius: 10px;
	border-radius: 10px;
}
div#play table td input#player1 {
	background-color:#222222;
	color:white;
	text-align:left;
}
div#play table td input#player2 {
	background-color:#CCCCCC;
	color:black;
	text-align:right;
}
</style>
<script>
var LastTouch;
var players;
var moving;
// pointer to timer that updates screen so it can be stopped later
var timer;
var fischerSecs;
var randomMinSecs;
var randomMaxSecs;
var timeWarningSecs;
var bronsteinSecs;
var simpleDelaySecs;
var keyboardLayout = "uk-qwerty";
var differentTimeForEachPlayer = false;
var mode;
var clockSpeed = 100;
var pauseStarted;

function stopTimer() {
	if (timer == undefined) return;
	clearInterval(timer);
	timer = undefined;
}

function init() {
	// in case we are half way throught a game now, stop the various code stuff
	stopTimer();
	document.onkeyup = keyDoNothing;
	// display proper screen
	document.getElementById('start').style.display = 'block';
	document.getElementById('options').style.display = 'block';
        document.getElementById('nojs').style.display = 'none';
        document.getElementById('play').style.display = 'none';
	document.getElementById('paused').style.display = 'none';
	// holds the time the currently running clock started
	LastTouch = false;
	// holds how much time each player has left in milliseconds
	players = new Array(0,0);
	// current state, -1 before start, -2 all over, 0 or 1: player moving
	moving = -1;
	// mode: normal, or one of the special modes
	mode = undefined;
	// fischer mode
	fischerSecs = new Array(0,0);
	// bronstein mode
	bronsteinSecs = new Array(0,0);
	// simple delay mode
	simpleDelaySecs = new Array(0,0);	
	// random
	randomMinSecs = new Array(0,0);
	randomMaxSecs = new Array(0,0);
	// warn by turning clocks red when there a certain number of seconds left, 0 to disable.
	timeWarningSecs = 0;
	// not in pause mode
	pauseStarted = false;
	// set ui to normal colours and size
	document.getElementById('player1').style.color = 'white';
	document.getElementById('player2').style.color = 'black';
	document.getElementById('player1').style.fontSize='300%';
	document.getElementById('player2').style.fontSize='300%';
}

function setError(id,message) {
	document.getElementById(id).innerHTML=message;
	document.getElementById(id).style.display = 'block';
}

function startMatch() {
	document.getElementById('errorStart').style.display = 'none';
	document.getElementById('errorFischer').style.display = 'none';
	document.getElementById('errorSimpleDelay').style.display = 'none';
	document.getElementById('errorBronstein').style.display = 'none';
	document.getElementById('errorRandom').style.display = 'none';
	// storing prefs in cookies as we go so we can load them later .......
	// calculate start time
	var time = Math.max(0,parseInt(document.getElementById('Hrs').value))*60*60 
		+ Math.max(0,parseInt(document.getElementById('Mins').value))*60
		+ Math.max(0,parseInt(document.getElementById('Secs').value));
	if (isNaN(time)) {
		setError('errorStart', 'We could not parse the time you requested as a recognised number. Please try again.');
		return;
	}
	if (time < 1) {
		setError('errorStart','You must set some time on the clocks. Please try again.');
		return;
	}
	setCookie('time',time);
	players[0] = time * 1000;
	players[1] = time * 1000;

	if (document.getElementById('DiffStartTimes').checked) {
		var timerhp = Math.max(0,parseInt(document.getElementById('HrsRHP').value))*60*60
			+ Math.max(0,parseInt(document.getElementById('MinsRHP').value))*60
			+ Math.max(0,parseInt(document.getElementById('SecsRHP').value));
		if (isNaN(timerhp)) {
			setError('errorStart','We could not parse the time you requested for the right hand player as a recognised number. Please try again.');
			return;
		}
		if (timerhp < 1) {
			setError('errorStart','You must set some time for the right hand player. Please try again.');
			return;
		}
		players[1] = timerhp * 1000;
		setCookie('diffTimes','y');
		setCookie('timeRHP',timerhp);
		differentTimeForEachPlayer = true;
	} else {
		setCookie('diffTimes','n');
		setCookie('timeRHP',0);
		differentTimeForEachPlayer = false;
	}

	// Fischer options
	if (document.getElementById('Fischer').checked) {
		fischerSecs = Math.max(0,parseInt(document.getElementById('FischerSecs').value));
		if (isNaN(fischerSecs)) {
			setError('errorFischer','We could not parse the number of seconds you requested as a recognised number. Please try again.');
			return;
		}
		fischerSecs = new Array( fischerSecs, fischerSecs );
		if (differentTimeForEachPlayer) {
			fischerSecs[1] = Math.max(0,parseInt(document.getElementById('FischerSecsRHP').value));
			if (isNaN(fischerSecs[1])) {
				setError('errorFischer','We could not parse the number of seconds you requested for the right hand player as a recognised number. Please try again');
                        	return;
                	}
			setCookie('fischerSecsRHP',fischerSecs[1]);
		}
		setCookie('fischerSecs',fischerSecs[0]);
		var ele = document.getElementById('FischerMode');
		if (ele.options[ele.selectedIndex].value == "0") { 
			mode = 'fischerBefore'; 
		} else { 
			mode = 'fischerAfter'; 
		}
	} else { 
		fischerSecs = new Array(0,0); 
	}

	// Bronstein
	if (document.getElementById('Bronstein').checked) {
		bronsteinSecs = Math.max(0,parseInt(document.getElementById('BronsteinSecs').value));
		if (isNaN(bronsteinSecs)) {
			setError('errorBronstein','We could not parse the number of seconds you requested as a recognised number. Please try again.');
			return;
		}
		bronsteinSecs =  new Array( bronsteinSecs, bronsteinSecs );
		if (differentTimeForEachPlayer) {
			bronsteinSecs[1] = Math.max(0,parseInt(document.getElementById('BronsteinSecsRHP').value));
			if (isNaN(bronsteinSecs[1])) {
				setError('errorBronstein','We could not parse the number of seconds you requested for the right hand player as a recognised number. Please try again.');
				return;
			}
			setCookie('bronsteinSecsRHP',bronsteinSecs[1]);
		}
		setCookie('bronsteinSecs',bronsteinSecs[0]);
		mode = 'bronstein';
	} else {
		bronsteinSecs = new Array(0,0);
	}

	// simpleDelaySeconds
        if (document.getElementById('SimpleDelay').checked) {
                simpleDelaySecs = Math.max(0,parseInt(document.getElementById('SimpleDelaySecs').value));
                if (isNaN(simpleDelaySecs)) {
                        setError('errorSimpleDelay', 'We could not parse the number of seconds you requested as a recognised number. Please try again.');
                        return;
                }
		simpleDelaySecs = new Array(simpleDelaySecs,simpleDelaySecs);
		if (differentTimeForEachPlayer) {
			simpleDelaySecs[1] = Math.max(0,parseInt(document.getElementById('SimpleDelaySecsRHP').value));
			if (isNaN(simpleDelaySecs[1])) {
				setError('errorSimpleDelay','We could not parse the number of seconds you requested for the right hand player as a recognised number. Please try again.');
				return;
			}
			setCookie('simpleDelaySecsRHP',simpleDelaySecs[1]);
		}
                setCookie('simpleDelaySecs',simpleDelaySecs[0]);
		mode = 'simpleDelay';
        } else {
                simpleDelaySecs = new Array(0,0);
        }

        // Random options
        if (document.getElementById('Random').checked) {
                randomMinSecs = Math.max(0,parseInt(document.getElementById('MinRandomSecs').value));
                if (isNaN(randomMinSecs)) {
                        setError('errorRandom','We could not parse the number of min seconds you requested as a recognised number. Please try again.');
                        return;
                }
                randomMinSecs = new Array( randomMinSecs, randomMinSecs );
                randomMaxSecs = Math.max(0,parseInt(document.getElementById('MaxRandomSecs').value));
                if (isNaN(randomMaxSecs)) {
                        setError('errorRandom','We could not parse the number of max seconds you requested as a recognised number. Please try again.');
                        return;
                }
                randomMaxSecs = new Array( randomMaxSecs, randomMaxSecs );
		if (randomMinSecs[0] >= randomMaxSecs[0]) {
			setError('errorRandom','Max must be more than min!');
                        return;
                }

                if (differentTimeForEachPlayer) {
                        randomMinSecs[1] = Math.max(0,parseInt(document.getElementById('MinRandomSecsRHP').value));
                        if (isNaN(randomMinSecs[1])) {
                                setError('errorRandom','We could not parse the min number of seconds you requested for the right hand player as a recognised number. Please try again');
                                return;
                        }
                        randomMaxSecs[1] = Math.max(0,parseInt(document.getElementById('MaxRandomSecsRHP').value));
                        if (isNaN(randomMaxSecs[1])) {
                                setError('errorRandom','We could not parse the max number of seconds you requested for the right hand player as a recognised number. Please try again');
                                return;
                        }
			if (randomMinSecs[1]  >= randomMaxSecs[1]){ 
				setError('errorRandom','Max must be more than min for the right hand player!');
				return;
                        }

                        setCookie('randomMinSecsRHP',randomMinSecs[1]);
			setCookie('randomMaxSecsRHP',randomMaxSecs[1]);
                }
                setCookie('fischerMinSecs',randomMinSecs[0]);
		setCookie('fischerMaxSecs',randomMaxSecs[0]);
                var ele = document.getElementById('RandomMode');
                if (ele.options[ele.selectedIndex].value == "0") {
                        mode = 'randomBefore';
                } else {
                        mode = 'randomAfter';
                }
        } else {
                randomMinSecs = new Array(0,0);
		randomMaxSecs = new Array(0,0);
        }



	document.getElementById('start').style.display = 'none';
	document.getElementById('options').style.display = 'none';
	document.getElementById('ReturnToMenuLinkFromGame').style.display = 'none';
	document.getElementById('PauseAndOptionsFromGame').style.display = 'block';
	document.getElementById('play').style.display = 'block';
	document.getElementById('SimpleDelayDisplay').style.textAlign='center';
	document.getElementById('SimpleDelayDisplay').innerHTML = 'The first player to move should click on their own clock to start the game.';

	setCookie('mode',mode);
	update();
	colourClocks(players[0],players[1]);
}

function userChangedSlowerClockOptions() {
	if (document.getElementById('SlowerClock').checked) {
		clockSpeed = 400; 
		setCookie('clockSpeed','slow');
	} else {
		clockSpeed = 100; 
		setCookie('clockSpeed','fast');
	}
}

function userChangedTimeWarningsOptions() {
	// Time Warning Options
	if (document.getElementById('TimeWarning').checked) {
		timeWarningSecs = Math.max(0,parseInt(document.getElementById('TimeWarningSecs').value));
		if (isNaN(timeWarningSecs)) {
                        setError('errorTimeWarnings','We could not parse the number of seconds you requested a warning at as a recognised number.');
                        timeWarningSecs = 0; 
			setCookie('timeWarning','off');
		} else {
			document.getElementById('errorTimeWarnings').style.display = 'none';
			setCookie('timeWarningSecs',timeWarningSecs);
			setCookie('timeWarning','on');
		}
	} else { 
		document.getElementById('errorTimeWarnings').style.display = 'none';       
		timeWarningSecs = 0; 
		setCookie('timeWarning','off');
	}

}

function update() {
	var timenow = new Array(players[0],players[1]);
	if (moving == 0 || moving == 1) {
		var now = new Date();
		var diff = now.getTime() - LastTouch.getTime() - simpleDelaySecs[moving]*1000;
		if (diff < 0) {
			document.getElementById('SimpleDelayDisplay').innerHTML = 'Delayed for '+renderTime(diff * -1);
			if (moving == 0) { 
				document.getElementById('SimpleDelayDisplay').style.textAlign='left';
			} else {
				document.getElementById('SimpleDelayDisplay').style.textAlign='right';
			}
			diff = 0;
		} else {
			document.getElementById('SimpleDelayDisplay').innerHTML = '&nbsp;';
		}
		timenow[moving] = timenow[moving] - diff;

		colourClocks(timenow[0],timenow[1]);
	}

	// if match has ended .......
	if (timenow[0] <= 0 || timenow[1] <= 0) { 
		if (timenow[0] <= 0) players[0] = 0; 
		if (timenow[1] <= 0) players[1] = 0; 
		moving = -2; 
		stopTimer(); 
		document.getElementById('ReturnToMenuLinkFromGame').style.display = 'block';
		document.getElementById('PauseAndOptionsFromGame').style.display = 'none';
	}

	document.getElementById('player1').value = renderTime(timenow[0]);
	document.getElementById('player2').value = renderTime(timenow[1]);

}

function renderTime(milliseconds) {
	if (milliseconds < 1) { return 'Lose'; }
	var seconds = parseInt(milliseconds / 1000);
	if (seconds >= 60*60) {
		return parseInt(seconds / (60*60))+":"+zeropad((seconds / 60)%60)+":"+zeropad(seconds%60);
	} else if ( seconds >= 60) {
		return parseInt(seconds / 60)+":"+zeropad(seconds%60);
	} else {
		return parseInt(seconds);
	}
	return out;
}
function zeropad(innum) {
	if (innum < 10) { return "0"+parseInt(innum); } else { return parseInt(innum); }
}

/* This func colours the players clocks depending on the time they have left and the settings.
   Could be called on any of those variables changing, so you must cover all eventualities. 
   These 2 params have to be passed in as it's not always possible to get this info from the global state. **/
function colourClocks(player1time,player2time) {
	// the +1000 is so that the timer turns red on the time set, and not just when below the time set.
	if (timeWarningSecs > 0 && player1time <= (timeWarningSecs * 1000 + 1000)) {
		document.getElementById('player1').style.color = 'red';
	} else {
		document.getElementById('player1').style.color = 'white';
	}
	if (timeWarningSecs > 0 && player2time <= (timeWarningSecs * 1000 + 1000)) {
		document.getElementById('player2').style.color = 'red';
	} else {
		document.getElementById('player2').style.color = 'black';
	}
}

function clickPlayer(player) {
	if (moving == -2) { return; }
	else if (player == moving) {
		// normal move
		// calculate diff, apply
		var now = new Date();
		var diff = now.getTime() - LastTouch.getTime() - simpleDelaySecs[moving]*1000;
		if (diff < 0) diff = 0;
		players[moving] = players[moving] - diff;
		// modes that add time after move
		if (mode == 'bronstein') players[moving] = players[moving] + Math.min(diff, bronsteinSecs[moving]*1000);
		else if (mode == 'fischerAfter') players[moving] = players[moving] + fischerSecs[moving] * 1000;
		else if (mode == 'randomAfter') {
                        var r = Math.floor(Math.random()*(randomMaxSecs[moving]-randomMinSecs[moving]+1)) + randomMinSecs[moving];
                        players[moving] = players[moving] + r*1000;
		}
		// switch players
		document.getElementById('player'+(moving+1)).style.fontSize='300%';
		if (player == 1 ) { moving = 0; } else { moving = 1; }
		document.getElementById('player'+(moving+1)).style.fontSize='800%';
		// modes that add time before a move
		if (mode == 'fischerBefore') players[moving] = players[moving] + fischerSecs[moving] * 1000;
		else if(mode == 'randomBefore') {
			var r = Math.floor(Math.random()*(randomMaxSecs[moving]-randomMinSecs[moving]+1)) + randomMinSecs[moving];
			players[moving] = players[moving] + r*1000; 
		}
		// we may have now added enought time that we have to turn clocks from red back to original colour ...
		//  ... however this is now handled in the call to update() below.
		// set up for this move, and ui.
		LastTouch = new Date();
		update();
		if (moving == 0) { document.getElementById('player1').focus(); } else {  document.getElementById('player2').focus(); }
	} else if (moving == -1) {
		// we are starting the match
		document.getElementById('SimpleDelayDisplay').innerHTML = '&nbsp;';
		document.onkeyup = key;
		moving = player;
		document.getElementById('player'+(moving+1)).style.fontSize='800%';
		//  modes that add time before a move
		if (mode == 'fischerBefore') players[moving] = players[moving] + fischerSecs[moving] * 1000;
		else if(mode == 'randomBefore') {
			var r = Math.floor(Math.random()*(randomMaxSecs[moving]-randomMinSecs[moving]+1)) + randomMinSecs[moving];
			players[moving] = players[moving] + r*1000;
		}
		// more setup
		timer = setInterval("update()",clockSpeed);
		LastTouch = new Date();
		update();
	}
}

function key(e) {
	// as we disable and re-enable the handler at appropiate points anyway (start, end, pause)
	// the next line is just for safety and isn't really needed. So commented out for now.
	//if (moving != 0 && moving != 1) return;
	var k = (window.event) ? event.keyCode : e.keyCode;
	if (keyboardLayout == "uk-qwerty") {
		if (k == 49 || k == 50 || k == 51 || k == 52 || k == 53 || k == 81 || k == 113 || k == 87 || k == 119 || k == 69 || k == 101 || k == 84 || k == 116 || k == 65 || k == 97 || k == 83 || k == 115 || k == 68 || k == 100 || k == 70 || k == 102 || k == 71 || k == 103 || k == 90 || k == 122 || k == 88 || k == 120 || k == 67 || k == 99 || k == 86 || k == 118) {
			clickPlayer(0);
		} else if (k == 54 || k == 55 || k == 56 || k == 57 || k == 48 || k == 89 || k == 121 || k == 85 || k == 117 || k == 73 || k == 105 || k == 79 || k == 111 || k == 80 || k == 112 || k == 72 || k == 104 || k == 74 || k == 105 || k == 74 || k == 106 || k == 75 || k == 107 || k == 76 || k == 108 || k == 66 || k == 98 || k == 78 || k == 110 || k == 77 || k == 109) {
			clickPlayer(1);
		}
	} else if (keyboardLayout == "uk-dvorak") {
		if ( k == 49 || k == 50 || k == 51 || k == 52 || k == 53 || k == 39 || k == 44 || k == 46 || k == 112 || k == 80 || k == 121 || k == 89 || k == 97 || k == 65 || k == 111 || k == 79 || k == 101 || k == 69 || k == 117 || k == 85 || k == 105 || k == 73 || k == 59 || k == 113 || k == 81 || k == 106 || k == 74 || k == 107 || k == 75 || k == 120 || k == 88) {
			clickPlayer(0);
		} else if ( k == 54 || k == 55 || k == 56 || k == 57 || k == 48 || k == 102 || k == 70 || k == 103 || k == 71 || k == 99 || k == 67 || k == 114 || k == 82 || k == 108 || k == 76 || k == 47 || k == 61 || k == 100 || k == 68 || k == 104 || k == 72 || k == 116 || k == 84 || k == 110 || k == 78 || k == 115 || k == 83 || k == 45 || k == 98 || k == 66 || k == 109 || k == 77 || k == 119 || k == 87 || k == 118 || k == 86 || k == 122 || k == 90 || k == 91 || k == 93){
			clickPlayer(1);
		}
	} else if (keyboardLayout == "numerickeypad") {
		// 1st 3 are normal numbers, for mobile phones, 2nd 3 are numeric keypad for PC's
		if ( k == 49 || k == 52 || k == 55 || k== 97 || k ==100 || k == 103 ) {
			clickPlayer(0);
		} else if ( k == 51 || k == 54 || k == 57 || k == 99 || k == 102 || k == 105 ){
			clickPlayer(1);
		}
	} else if (keyboardLayout == "finnish") {
		if ( k == 167 || k == 49 || k == 50 || k == 51 || k == 52 || k == 53 || k == 113 || k == 81 || k == 119 || k == 87 || k == 101 || k == 69 || k == 114 || k == 82 || k == 116 || k == 84 || k == 97 || k == 65 || k == 115 || k == 83 || k == 100 || k == 68 || k == 102 || k == 70 || k == 103 || k == 71 || k == 60 || k == 122 || k == 90 || k == 120 || k == 88 || k == 99 || k == 67 || k == 118 || k == 86 || k == 120 ) {
			clickPlayer(0);
		} else if ( k == 54 || k == 55 || k == 56 || k == 57 || k == 48 || k == 43 || k == 253 || k == 117 || k == 85 || k == 105 || k == 73 || k == 111 || k== 79 || k == 112 || k == 80 || k == 229 || k == 255 || k == 121 || k == 89 || k == 104 || k == 72 || k == 106 || k == 74 || k == 107 || k == 75 || k == 108 || k == 76 || k == 246 || k == 228 || k == 39 || k == 98 || k == 66 || k == 110 || k == 78 || k == 109 || k == 77 || k == 44 || k == 46 || k == 45){
			clickPlayer(1);
		}
	}
}

function keyDoNothing(e) {}

function reset() {
	if (moving == 0 || moving == 1) {
		if (confirm('Are you sure you want to reset the current game?')) init();
	} else {
		init();
	}
}

function startPause() {
	if ((moving == 0 || moving == 1) && !pauseStarted) {
		stopTimer();
		pauseStarted = new Date();
		document.getElementById('play').style.display = 'none';
		document.getElementById('paused').style.display = 'block';
		document.getElementById('options').style.display = 'block';
		document.onkeyup = keyDoNothing;
	}
	if (moving == -1 && !pauseStarted) {
		document.getElementById('play').style.display = 'none';
        	document.getElementById('paused').style.display = 'block';
        	document.getElementById('options').style.display = 'block';
        	document.onkeyup = keyDoNothing;
	}
}

function endPause() {
	document.getElementById('paused').style.display = 'none';
	document.getElementById('options').style.display = 'none';
	document.getElementById('play').style.display = 'block';
	document.onkeyup = key;
	if (moving > -1) {
		colourClocks(players[0],players[1]); // bug, this should really take into account the time elapsed this move.
		var now = new Date();
		LastTouch.setTime(LastTouch.getTime() + (now.getTime() - pauseStarted.getTime()));	
		pauseStarted = false;
		timer = setInterval("update()",clockSpeed);
	}
}

function confirmExit() {
	if (moving == 0 || moving == 1) {
		startPause();
		return 'Are you sure you want to navagiate away from this page? This will lose the current game.';
	}
}
window.onbeforeunload = confirmExit;

function setCookie(name,value) {
	var date = new Date();
	date.setTime(date.getTime()+(100*24*60*60*1000));
	document.cookie = "bc"+name+"="+value+"; expires="+date.toGMTString();
}

function getCookie(name) {
        var cookieBits = document.cookie.split(';');
        for(var i=0;i < cookieBits.length;i++) {
                var cookie = cookieBits[i];
                while (cookie.charAt(0)==' ') cookie = cookie.substring(1,cookie.length);
                if (cookie.indexOf('bc'+name+'=') == 0) return cookie.substring(1+2+name.length,cookie.length);
	}
}

function onPageLoad() {
	// start time
	var time = getCookie('time');
	if (!isNaN(time) && time > 0) {
		document.getElementById('Hrs').value = parseInt(time / (60*60)); 
		document.getElementById('Mins').value = (parseInt(time / 60)%60);
		document.getElementById('Secs').value = parseInt(time%60);
	}

	if (getCookie('diffTimes') == 'y') {
		document.getElementById('DiffStartTimes').checked = time;
		diffStartTimesForm(true);
		var timerhp = getCookie('timeRHP');
		if (!isNaN(timerhp) && timerhp > 0) {
			document.getElementById('HrsRHP').value = parseInt(timerhp / (60*60));
			document.getElementById('MinsRHP').value = (parseInt(timerhp / 60)%60);
			document.getElementById('SecsRHP').value = parseInt(timerhp%60);
		}
	} else {
		document.getElementById('DiffStartTimes').checked = false;
		diffStartTimesForm(false);
	}

	// note in all that follows, even if the option is turned off the settings are still loaded.
	// we want to load as much of the users last choices as possible, for a more friendly UI.

	// fischer
	if (getCookie('mode') == 'fischerBefore') {
		selectMode('Fischer');
		document.getElementById('FischerMode').selectedIndex = 0;
	} else if (getCookie('mode') == 'fischerAfter') {
		selectMode('Fischer');
		document.getElementById('FischerMode').selectedIndex = 1;
	}
	if (getCookie('fischerSecs')) document.getElementById('FischerSecs').value = getCookie('fischerSecs');
	if (getCookie('fischerSecsRHP')) document.getElementById('FischerSecsRHP').value = getCookie('fischerSecsRHP');

	// bronstein
	if (getCookie('bronsteinSecs')) document.getElementById('BronsteinSecs').value = getCookie('bronsteinSecs');
	if (getCookie('bronsteinSecsRHP')) document.getElementById('BronsteinSecsRHP').value = getCookie('bronsteinSecsRHP');
	if (getCookie('mode') == 'bronstein') selectMode('Bronstein');

	// simple delay
	if (getCookie('simpleDelaySecs')) document.getElementById('SimpleDelaySecs').value = getCookie('simpleDelaySecs');
	if (getCookie('simpleDelaySecsRHP')) document.getElementById('SimpleDelaySecsRHP').value = getCookie('simpleDelaySecsRHP');
        if (getCookie('mode') == 'simpleDelay') selectMode('SimpleDelay');

	// random
	if (getCookie('randomMin')) document.getElementById('RandomMin').value = getCookie('randomMin');
	if (getCookie('randomMax')) document.getElementById('RandomMax').value = getCookie('randomMax');
 	if (getCookie('randomMinRHP')) document.getElementById('RandomMinRHP').value = getCookie('randomMinRHP');
	if (getCookie('randomMMaxRHP')) document.getElementById('RandomMaxRHP').value = getCookie('randomMaxRHP');	
	if (getCookie('mode') == 'randomBefore') {
		selectMode('Random');
		document.getElementById('RandomMode').selectedIndex = 0;
	} else if (getCookie('mode') == 'randomAfter') {
                selectMode('Random');
                document.getElementById('RandomMode').selectedIndex = 1;
	}

	// time warnings
	// default is on, so we only need to check if user turned it off.
	if (getCookie('timeWarning') == 'off') document.getElementById('TimeWarning').checked = false;
	if (getCookie('timeWarningSecs')) document.getElementById('TimeWarningSecs').value = getCookie('timeWarningSecs');
	// now call this to ensure global state variables are set correctly.
	userChangedTimeWarningsOptions();

	// Clock Speed
	if (getCookie('clockSpeed') == "slow") {
		document.getElementById('SlowerClock').checked = true;
		// now call this to ensure global state variables are set correctly.
		userChangedSlowerClockOptions();
	}

	// keyboard layout
	var kbLayout = getCookie('kbLayout');
	if (kbLayout) {
		var ele =  document.getElementById('KbLayout');
		for(var i = 0; i < ele.length; i++) {
			if (ele.options[i].value == kbLayout) {
				ele.selectedIndex = i;
				keyboardLayout = ele.options[i].value;
			} 
		}
	}
}

function diffStartTimesForm(show) {
	if (show) {
		document.getElementById('StartTimeForRightPlayer').style.display = 'block';
		document.getElementById('ForLHSPlayerLabel').style.display = 'inline';
		document.getElementById('ForRHSPlayerFischer').style.display = 'inline';
		document.getElementById('ForRHSPlayerSimpleDelay').style.display = 'inline';
		document.getElementById('ForRHSPlayerBronstein').style.display = 'inline';
		document.getElementById('ForRHSPlayerRandom').style.display = 'inline';
		document.getElementById('HrsRHP').value = document.getElementById('Hrs').value;
		document.getElementById('MinsRHP').value = document.getElementById('Mins').value;
		document.getElementById('SecsRHP').value = document.getElementById('Secs').value;
		document.getElementById('FischerSecsRHP').value = document.getElementById('FischerSecs').value;
		document.getElementById('SimpleDelaySecsRHP').value = document.getElementById('SimpleDelaySecs').value;
		document.getElementById('BronsteinSecsRHP').value = document.getElementById('BronsteinSecs').value;
		document.getElementById('MinRandomSecsRHP').value = document.getElementById('MinRandomSecs').value;
		document.getElementById('MaxRandomSecsRHP').value = document.getElementById('MaxRandomSecs').value;
	} else {
		document.getElementById('StartTimeForRightPlayer').style.display = 'none';
		document.getElementById('ForLHSPlayerLabel').style.display = 'none';
		document.getElementById('ForRHSPlayerFischer').style.display = 'none';
		document.getElementById('ForRHSPlayerSimpleDelay').style.display = 'none';
		document.getElementById('ForRHSPlayerBronstein').style.display = 'none';
		document.getElementById('ForRHSPlayerRandom').style.display = 'none';
	}
}
function selectMode(newMode) {
	// this function could be called because the user clicked something or we are setting the users last used options from their cookies. In the latter case this line is needed, but but not the former.
	if (document.getElementById(newMode) && !document.getElementById(newMode).checked) document.getElementById(newMode).checked = true;
	var modes = new Array('Fischer','SimpleDelay','Bronstein','Random');
	for (var i in modes) {
		// avoid flickering screens, as this function is called on many events: so don't want to hide then show a split second later.
		if (modes[i] != newMode) {
			document.getElementById(modes[i]+'ShortText').style.display = 'inline';
			document.getElementById(modes[i]+'Options').style.display = 'none';
		}
	}
	if (newMode != 'Normal') {
		document.getElementById(newMode+'ShortText').style.display = 'none';
		document.getElementById(newMode+'Options').style.display = 'inline';
	}
}
</script>
</head>
<body onload="init(); onPageLoad();">

<div id="nojs">
	 Loading, please wait ... 
</div>
<noscript>
	You seem not to have JavaScript enabled. Without it,  <a href="http://code.google.com/p/bobchess/">BobChess</a> will not run. 
</noscript>

<div id="play"  style="display: none;">
	<div id="SimpleDelayDisplay">&nbsp;</div> 
	<table><tr><td>
		<input type="button" id="player1" onclick="clickPlayer(0);">
	</td><td >
		<input type="button" id="player2" onclick="clickPlayer(1);">
	</td></tr></table>
	<div>
		<span id="PauseAndOptionsFromGame">(<a href="#" onclick="startPause(); return false;">pause & other options</a>)</span>
		<span id="ReturnToMenuLinkFromGame"><input type="button" value="Return to menu  &gt; &gt; &gt;" onclick="reset(); return false;"></span>
	</div>
</div>

<div id="start" style="display: none;">
	<h1>BobChess Online Chess Clock</h1>
	<form>
		<div class="helpbox">
			<h2>Instructions</h2>
			<p>When a players clock is running, they can press a number or letter key on their side of the keyboard or click their clock with the mouse to end their go and start their opponents clock running.</p>
			<p>There is a pause button on the bottom of the screen.</p>
			<p><em>This is Open Source. If you want to download a copy of this program to use when not connected to the internet, simply select 'file' and 'save' in your web browser. <a href="http://code.google.com/p/bobchess/" style="color: white;">Find out more here</a></em></p>
		</div>
		<fieldset>
			<legend>Start Time</legend>
			<span id="errorStart" class="error"></span>
			<p>Start Time <span id="ForLHSPlayerLabel" style="display: none;">for left hand player</span>: <input type=text id="Hrs" size="2" value="0">hrs:<input type=text id="Mins" size="2" value="5">mins:<input type=text id="Secs" size="2" value="00">secs</p>
			<p id="StartTimeForRightPlayer" style="display: none;">Start Time for right hand player: <input type=text id="HrsRHP" size="2" value="0">hrs:<input type=text id="MinsRHP" size="2" value="5">mins:<input type=text id="SecsRHP" size="2" value="00">secs</p>
			<p><input type="checkbox" id="DiffStartTimes" onclick="diffStartTimesForm(this.checked);"><label for="DiffStartTimes">Different times for each player</label></p>
		</fieldset>
		<fieldset>
			<legend>Mode</legend>
			<p>
				<input type="radio" name="Mode" id="NormalChess" checked="checked" onchange="if (this.checked) selectMode('Normal');" onclick="if (this.checked) selectMode('Normal');" onkeyup="if (this.checked) selectMode('Normal');">
				<label for="NormalChess">Normal Chess Clock</label>
			</p>
			<span id="errorFischer" class="error"></span>
			<p>
				<input type="radio" name="Mode" id="Fischer" onchange="if (this.checked) selectMode('Fischer');" onclick="if (this.checked) selectMode('Fischer');" onkeyup="if (this.checked) selectMode('Fischer');">
				<span id="FischerShortText">
					<label for="Fischer">Fischer Clock; add some time before or after every move</label>
				</span>
				<span id="FischerOptions" style="display: none;">
					<label for="Fischer">Fischer Clock; add </label><input type="text" id="FischerSecs" value="5" size="2"> seconds 
					<span id="ForRHSPlayerFischer"  style="display: none;"> for the left hand player and <input type="text" id="FischerSecsRHP" value="5" size="2"> seconds for the right hand player</span> 
					<select id="FischerMode"><option value=0>Before</option><option value=1>After</option></select> every move.
				</span>
			</p>
			<span id="errorSimpleDelay" class="error"></span>
			<p>
				<input type="radio" name="Mode" id="SimpleDelay" onchange="if (this.checked) selectMode('SimpleDelay');" onclick="if (this.checked) selectMode('SimpleDelay');" onkeyup="if (this.checked) selectMode('SimpleDelay');">
				<span id="SimpleDelayShortText">
					<label for="SimpleDelay">Simple Delay; every move the clock waits before starting</label>
				</span>
				<span id="SimpleDelayOptions" style="display: none;">
					<label for="SimpleDelay">Simple Delay; every move the clock waits </label><input type="text" id="SimpleDelaySecs" value="5" size="2"> seconds 
					<span id="ForRHSPlayerSimpleDelay"  style="display: none;">for the left hand player and <input type="text" id="SimpleDelaySecsRHP" value="5" size="2"> seconds for the right hand player</span> before starting.
				</span>
			</p>
			<span id="errorBronstein" class="error"></span>
			<p>
				<input type="radio" name="Mode" id="Bronstein" onchange="if (this.checked) selectMode('Bronstein');" onclick="if (this.checked) selectMode('Bronstein');" onkeyup="if (this.checked) selectMode('Bronstein');">
				<span id="BronsteinShortText">
					<label for="Bronstein">Bronstein Clock; the amount of time the player takes is added to their clock at the end of their move up to a certain limit</label>
				</span>
				<span id="BronsteinOptions" style="display: none;">
					<label for="Bronstein">Bronstein Clock; the amount of time the player takes is added to their clock at the end of their move up to a limit of </label><input type="text" name="BronsteinSecs" id="BronsteinSecs" size="2" value="5"> seconds 
					<span id="ForRHSPlayerBronstein"  style="display: none;">for the left hand player and <input type="text" id="BronsteinSecsRHP" size="2" value="5"> seconds for the right hand player</span>.
				</span>
			</p>
                        <span id="errorRandom" class="error"></span>
                        <p>
                                <input type="radio" name="Mode" id="Random" onchange="if (this.checked) selectMode('Random');" onclick="if (this.checked) selectMode('Random');" onkeyup="if (this.checked) selectMode('Random');">
                                <span id="RandomShortText">
                                        <label for="Random">Random Fischer Clock; add some random amount of time before or after every move.</label>
                                </span>
                                <span id="RandomOptions" style="display: none;">
                                        <label for="Random">Random Clock; add from </label><input type="text" id="MinRandomSecs" value="5" size="2"> to <input type="text" id="MaxRandomSecs" value="60" size="2"> seconds
                                        <span id="ForRHSPlayerRandom"  style="display: none;"> for the left hand player and from <input type="text" id="MinRandomSecsRHP" value="5" size="2"> to <input type="text" id="MaxRandomSecsRHP" value="60" size="2"> seconds for the right hand</span>
                                        <select id="RandomMode"><option value=0>Before</option><option value=1>After</option></select> every move. 
                                </span>
                        </p>

		</fieldset>
		<p><input style="font-size: 200%; padding: 10px" value="Start The Match" type=submit onclick="startMatch(); return false;"></p>
	</form>
</div>



<div id="paused" style=" display: none; text-align: center;">
	<p>The clocks are paused.</p> 
	<p><input type="button" onclick="endPause(); return false;" value="Continue current game &gt; &gt; &gt;"></p>
	<p><input type="button" value="Quit game and return to menu  &gt; &gt; &gt;" onclick="reset(); return false;"></p>
</div>

<div id="options" style="display: none;">
	<fieldset>
		<legend>Options</legend>
		<span id="errorTimeWarnings" class="error"></span>
		<p><input type="checkbox" name="TimeWarning" id="TimeWarning" checked="checked" onchange="userChangedTimeWarningsOptions();"><label for="TimeWarning">Turn clocks red when there is only</label> <input type="text" name=""TimeWarningSecs" id="TimeWarningSecs" size="2" value="5" onchange="userChangedTimeWarningsOptions();"> seconds left.</p>
		<p>Keyboard Layout: 
		<select id="KbLayout" onchange="keyboardLayout = this.value; setCookie('kbLayout',this.value);">
			<option value="uk-qwerty" selected>UK/USA</option>
			<option value="uk-dvorak">UK/USA Dvorak</option>
			<option value="finnish">Finnish/Swedish/Norwegian</option>
			<option value="numerickeypad">Numeric Keypad with num lock on (Left:1,4,7 Right: 3,6,9)</option> 
		</select> <a href="http://code.google.com/p/bobchess/wiki/KeyboardLayouts" target="_blank">Add More</a></p>
		<p><input type="checkbox" name="SlowerClock" id="SlowerClock" onchange="userChangedSlowerClockOptions();"><label for="SlowerClock">Slower screen-updates. (Use on slower computers)</label></p>
	</fieldset>
</div>

</body>
</html>
